package com.c.cojbackendquestionservice.controller;

import cn.hutool.extra.mail.MailUtil;
import com.alibaba.csp.sentinel.Entry;
import com.alibaba.csp.sentinel.EntryType;
import com.alibaba.csp.sentinel.SphU;
import com.alibaba.csp.sentinel.slots.block.BlockException;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.c.cojbackendcommon.annotation.AuthCheck;
import com.c.cojbackendcommon.common.BaseResponse;
import com.c.cojbackendcommon.common.DeleteRequest;
import com.c.cojbackendcommon.common.ErrorCode;
import com.c.cojbackendcommon.common.ResultUtils;
import com.c.cojbackendcommon.constant.RedisConstant;
import com.c.cojbackendcommon.constant.UserConstant;
import com.c.cojbackendcommon.exception.BusinessException;
import com.c.cojbackendcommon.exception.ThrowUtils;
import com.c.cojbackendmodel.model.dto.question.*;
import com.c.cojbackendmodel.model.dto.questionsubmit.QuestionSubmitAddRequest;
import com.c.cojbackendmodel.model.dto.questionsubmit.QuestionSubmitQueryDTO;
import com.c.cojbackendmodel.model.dto.questionsubmit.QuestionSubmitQueryRequest;
import com.c.cojbackendmodel.model.entity.Question;
import com.c.cojbackendmodel.model.entity.QuestionSubmit;
import com.c.cojbackendmodel.model.entity.User;
import com.c.cojbackendmodel.model.enums.QuestionSubmitLanguageEnum;
import com.c.cojbackendmodel.model.vo.*;
import com.c.cojbackendquestionservice.manager.AiManager;
import com.c.cojbackendquestionservice.manager.AiMangerFactory;
import com.c.cojbackendquestionservice.manager.AiModel;
import com.c.cojbackendquestionservice.manager.RedisLimiterManager;
import com.c.cojbackendquestionservice.service.QuestionService;
import com.c.cojbackendquestionservice.service.QuestionSubmitService;
import com.c.cojbackendserviceclient.service.UserFeignClient;
import com.google.gson.Gson;

import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.BeanUtils;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.web.bind.annotation.*;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import java.util.List;
import java.util.concurrent.TimeUnit;

import static com.c.cojbackendcommon.constant.RedisConstant.CACHE_KEY_PREFIX;

/**
 * 题目接口
 */
@RestController
@RequestMapping("/")
@Slf4j
public class QuestionController {

    @Resource
    private QuestionService questionService;

    @Resource
    private UserFeignClient userFeignClient;

    @Resource
    private QuestionSubmitService questionSubmitService;

    @Resource
    private RedisTemplate redisTemplate;

    @Resource
    private AiManager aiManager;

    @Resource
    private RedisLimiterManager redisLimiterManager;

    @Resource
    private AiMangerFactory aiMangerFactory;

    private final static Gson GSON = new Gson();

    // region 增删改查

    /**
     * 创建
     *
     * @param questionAddRequest
     * @param request
     * @return
     */
    @PostMapping("/add")
    public BaseResponse<Long> addQuestion(@RequestBody QuestionAddRequest questionAddRequest, HttpServletRequest request) {
        if (questionAddRequest == null) {
            throw new BusinessException(ErrorCode.PARAMS_ERROR);
        }
        Question question = new Question();
        BeanUtils.copyProperties(questionAddRequest, question);
        List<String> tags = questionAddRequest.getTags();
        if (tags != null) {
            question.setTags(GSON.toJson(tags));
        }
        List<JudgeCase> judgeCase = questionAddRequest.getJudgeCase();
        if (judgeCase != null) {
            question.setJudgeCase(GSON.toJson(judgeCase));
        }
        JudgeConfig judgeConfig = questionAddRequest.getJudgeConfig();
        if (judgeConfig != null) {
            question.setJudgeConfig(GSON.toJson(judgeConfig));
        }
        questionService.validQuestion(question, true);
        User loginUser = userFeignClient.getLoginUser(request);
        question.setUserId(loginUser.getId());
        question.setFavourNum(0);
        question.setThumbNum(0);
        boolean result = questionService.save(question);
        ThrowUtils.throwIf(!result, ErrorCode.OPERATION_ERROR);
        long newQuestionId = question.getId();
        return ResultUtils.success(newQuestionId);
    }

    /**
     * 删除
     *
     * @param deleteRequest
     * @param request
     * @return
     */
    @PostMapping("/delete")
    public BaseResponse<Boolean> deleteQuestion(@RequestBody DeleteRequest deleteRequest, HttpServletRequest request) {
        if (deleteRequest == null || deleteRequest.getId() <= 0) {
            throw new BusinessException(ErrorCode.PARAMS_ERROR);
        }
        User user = userFeignClient.getLoginUser(request);
        long id = deleteRequest.getId();
        // 判断是否存在
        Question oldQuestion = questionService.getById(id);
        ThrowUtils.throwIf(oldQuestion == null, ErrorCode.NOT_FOUND_ERROR);
        // 仅本人或管理员可删除
        if (!oldQuestion.getUserId().equals(user.getId()) && !userFeignClient.isAdmin(user)) {
            throw new BusinessException(ErrorCode.NO_AUTH_ERROR);
        }
        boolean b = questionService.removeById(id);
        return ResultUtils.success(b);
    }

    /**
     * 更新（仅管理员）
     *
     * @param questionUpdateRequest
     * @return
     */
    @PostMapping("/update")
    @AuthCheck(mustRole = UserConstant.ADMIN_ROLE)
    public BaseResponse<Boolean> updateQuestion(@RequestBody QuestionUpdateRequest questionUpdateRequest) {
        if (questionUpdateRequest == null || questionUpdateRequest.getId() <= 0) {
            throw new BusinessException(ErrorCode.PARAMS_ERROR);
        }
        Question question = new Question();
        BeanUtils.copyProperties(questionUpdateRequest, question);
        List<String> tags = questionUpdateRequest.getTags();
        if (tags != null) {
            question.setTags(GSON.toJson(tags));
        }
        List<JudgeCase> judgeCase = questionUpdateRequest.getJudgeCase();
        if (judgeCase != null) {
            question.setJudgeCase(GSON.toJson(judgeCase));
        }
        JudgeConfig judgeConfig = questionUpdateRequest.getJudgeConfig();
        if (judgeConfig != null) {
            question.setJudgeConfig(GSON.toJson(judgeConfig));
        }
        // 参数校验
        questionService.validQuestion(question, false);
        long id = questionUpdateRequest.getId();
        // 判断是否存在
        Question oldQuestion = questionService.getById(id);
        ThrowUtils.throwIf(oldQuestion == null, ErrorCode.NOT_FOUND_ERROR);
        boolean result = questionService.updateById(question);
        return ResultUtils.success(result);
    }

    /**
     * 根据 id 获取
     *
     * @param id
     * @return
     */
    @GetMapping("/get")
    public BaseResponse<Question> getQuestionById(long id, HttpServletRequest request) {
        if (id <= 0) {
            throw new BusinessException(ErrorCode.PARAMS_ERROR);
        }
        Question question = questionService.getById(id);
        if (question == null) {
            throw new BusinessException(ErrorCode.NOT_FOUND_ERROR);
        }
        User loginUser = userFeignClient.getLoginUser(request);
        // 不是本人或管理员，不能直接获取所有信息
        if (!question.getUserId().equals(loginUser.getId()) && !userFeignClient.isAdmin(loginUser)) {
            throw new BusinessException(ErrorCode.NO_AUTH_ERROR);
        }
        return ResultUtils.success(question);
    }

    /**
     * 根据 id 获取（脱敏）
     *
     * @param id
     * @return
     */
    @GetMapping("/get/vo")
    public BaseResponse<QuestionVO> getQuestionVOById(long id, HttpServletRequest request) {
        if (id <= 0) {
            throw new BusinessException(ErrorCode.PARAMS_ERROR);
        }
        Question question = questionService.getById(id);
        if (question == null) {
            throw new BusinessException(ErrorCode.NOT_FOUND_ERROR);
        }
        return ResultUtils.success(questionService.getQuestionVO(question, request));
    }

    /**
     * 分页获取列表（封装类）
     *
     * @param questionQueryRequest
     * @param request
     * @return
     */
    @PostMapping("/list/page/vo")
    public BaseResponse<Page<QuestionVO>> listQuestionVOByPage(@RequestBody QuestionQueryRequest questionQueryRequest,
                                                               HttpServletRequest request) {
        long current = questionQueryRequest.getCurrent();
        long size = questionQueryRequest.getPageSize();
        // 限制爬虫
        ThrowUtils.throwIf(size > 20, ErrorCode.PARAMS_ERROR);
        Page<Question> questionPage = questionService.page(new Page<>(current, size),
                questionService.getQueryWrapper(questionQueryRequest));
        return ResultUtils.success(questionService.getQuestionVOPage(questionPage, request));
    }

    /**
     * 分页获取当前用户创建的资源列表
     *
     * @param questionQueryRequest
     * @param request
     * @return
     */
    @PostMapping("/my/list/page/vo")
    public BaseResponse<Page<QuestionVO>> listMyQuestionVOByPage(@RequestBody QuestionQueryRequest questionQueryRequest,
                                                                 HttpServletRequest request) {
        if (questionQueryRequest == null) {
            throw new BusinessException(ErrorCode.PARAMS_ERROR);
        }
        User loginUser = userFeignClient.getLoginUser(request);
        questionQueryRequest.setUserId(loginUser.getId());
        long current = questionQueryRequest.getCurrent();
        long size = questionQueryRequest.getPageSize();
        // 限制爬虫
        ThrowUtils.throwIf(size > 20, ErrorCode.PARAMS_ERROR);
        Page<Question> questionPage = questionService.page(new Page<>(current, size),
                questionService.getQueryWrapper(questionQueryRequest));
        return ResultUtils.success(questionService.getQuestionVOPage(questionPage, request));
    }

    /**
     * 分页获取题目列表（仅管理员）
     *
     * @param questionQueryRequest
     * @param request
     * @return
     */
    @PostMapping("/list/page")
    @AuthCheck(mustRole = UserConstant.ADMIN_ROLE)
    public BaseResponse<Page<Question>> listQuestionByPage(@RequestBody QuestionQueryRequest questionQueryRequest,
                                                           HttpServletRequest request) {
        long current = questionQueryRequest.getCurrent();
        long size = questionQueryRequest.getPageSize();
        Page<Question> questionPage = questionService.page(new Page<>(current, size),
                questionService.getQueryWrapper(questionQueryRequest));
        return ResultUtils.success(questionPage);
    }

    // endregion

    /**
     * 编辑（用户）
     *
     * @param questionEditRequest
     * @param request
     * @return
     */
    @PostMapping("/edit")
    public BaseResponse<Boolean> editQuestion(@RequestBody QuestionEditRequest questionEditRequest, HttpServletRequest request) {
        if (questionEditRequest == null || questionEditRequest.getId() <= 0) {
            throw new BusinessException(ErrorCode.PARAMS_ERROR);
        }
        Question question = new Question();
        BeanUtils.copyProperties(questionEditRequest, question);
        List<String> tags = questionEditRequest.getTags();
        if (tags != null) {
            question.setTags(GSON.toJson(tags));
        }
        List<JudgeCase> judgeCase = questionEditRequest.getJudgeCase();
        if (judgeCase != null) {
            question.setJudgeCase(GSON.toJson(judgeCase));
        }
        JudgeConfig judgeConfig = questionEditRequest.getJudgeConfig();
        if (judgeConfig != null) {
            question.setJudgeConfig(GSON.toJson(judgeConfig));
        }
        // 参数校验
        questionService.validQuestion(question, false);
        User loginUser = userFeignClient.getLoginUser(request);
        long id = questionEditRequest.getId();
        // 判断是否存在
        Question oldQuestion = questionService.getById(id);
        ThrowUtils.throwIf(oldQuestion == null, ErrorCode.NOT_FOUND_ERROR);
        // 仅本人或管理员可编辑
        if (!oldQuestion.getUserId().equals(loginUser.getId()) && !userFeignClient.isAdmin(loginUser)) {
            throw new BusinessException(ErrorCode.NO_AUTH_ERROR);
        }
        boolean result = questionService.updateById(question);
        return ResultUtils.success(result);
    }

    /**
     * 提交代码
     *
     * @param questionSubmitAddRequest
     * @param request
     * @return resultNum
     */
    @PostMapping("/question_submit/do")
    public BaseResponse<Long> doQuestionSubmit(@RequestBody QuestionSubmitAddRequest questionSubmitAddRequest,
                                               HttpServletRequest request) {
        String userId = request.getHeader("X-user-Id");
        try (Entry entry = SphU.entry("questionSubmit", EntryType.IN, 1, userId)) {
            if (questionSubmitAddRequest == null || questionSubmitAddRequest.getQuestionId() <= 0) {
                throw new BusinessException(ErrorCode.PARAMS_ERROR);
            }
            // 登录才能提交代码
            final User loginUser = userFeignClient.getLoginUser(request);
            long questionSubmitId = questionSubmitService.doQuestionSubmit(questionSubmitAddRequest, loginUser);
            return ResultUtils.success(questionSubmitId);
        } catch (BlockException e) {
            MailUtil.send("2237210992@qq.com", "提交代码限流告警", "->该用户" + userId + "频繁提交代码", false);
            throw new BusinessException(ErrorCode.TOO_MANY_REQUEST);
        }
    }

    /**
     * 分页获取题目提交列表（除了管理员外，普通用户只能看到非答案、提交代码等公开信息）
     *
     * @param questionSubmitQueryRequest
     * @param request
     * @return
     */
    @PostMapping("/question_submit/list/page")
    public BaseResponse<Page<QuestionSubmitVO>> listQuestionSubmitByPage(@RequestBody QuestionSubmitQueryRequest questionSubmitQueryRequest,
                                                                         HttpServletRequest request) {
        long current = questionSubmitQueryRequest.getCurrent();
        long size = questionSubmitQueryRequest.getPageSize();
        // 从数据库中查询原始的题目提交分页信息
        Page<QuestionSubmit> questionSubmitPage = questionSubmitService.page(new Page<>(current, size),
                questionSubmitService.getQueryWrapper(questionSubmitQueryRequest));
        final User loginUser = userFeignClient.getLoginUser(request);
        // 返回脱敏信息
        return ResultUtils.success(questionSubmitService.getQuestionSubmitVOPage(questionSubmitPage, loginUser));
    }

    /**
     * 返回近日热题列表
     *
     * @param questionQueryRequest
     * @param request
     * @return
     */
    @PostMapping("/hot/list")
    public BaseResponse<Page<HotQuestionVO>> getHotQuestionSubmitList(@RequestBody QuestionQueryRequest questionQueryRequest, HttpServletRequest request) {
        User loginUser = userFeignClient.getLoginUser(request);
        questionQueryRequest.setUserId(loginUser.getId());
        // 尝试从缓存获取
        String cacheKey = RedisConstant.HOT_QUESTIONS;
        Page<HotQuestionVO> cachedHotQuestionVO = (Page<HotQuestionVO>) redisTemplate.opsForValue().get(cacheKey);
        if (cachedHotQuestionVO != null) {
            return ResultUtils.success(cachedHotQuestionVO);
        }
        Page<HotQuestionVO> questionVOPage = questionService.listHotQuestions(questionQueryRequest);
        // 设置缓存，过期时间1小时
        redisTemplate.opsForValue().set(cacheKey, questionVOPage, 1, TimeUnit.HOURS);
        return ResultUtils.success(questionVOPage);
    }

    /**
     * 获取排行榜
     *
     * @return
     */
    @GetMapping("/leaderboard")
    public BaseResponse<List<UserLeaderboardVO>> getLeaderboard() {
        // 调用questionSubmitService的getLeaderboard方法获取排行榜
        // 尝试从缓存获取
        String cacheKey = RedisConstant.LEADERBOARD;
        List<UserLeaderboardVO> cachedLeaderboard = (List<UserLeaderboardVO>) redisTemplate.opsForValue().get(cacheKey);
        if (cachedLeaderboard != null) {
            return ResultUtils.success(cachedLeaderboard);
        }
        List<UserLeaderboardVO> leaderboardVOS = questionSubmitService.getLeaderboard();
        // 设置缓存，过期时间1小时
        redisTemplate.opsForValue().set(cacheKey, leaderboardVOS, 1, TimeUnit.HOURS);
        return ResultUtils.success(leaderboardVOS);
    }


    /**
     * ai答题
     */
    @PostMapping("/question/ai")
    public BaseResponse<AiQuestionVO> aiQuestion(@RequestBody QuestionSubmitQueryDTO questionSubmitQueryDTO, HttpServletRequest request) {
        if (questionSubmitQueryDTO == null || questionSubmitQueryDTO.getQuestionId() <= 0) {
            throw new BusinessException(ErrorCode.PARAMS_ERROR);
        }
        //如果没设编程语言，则默认设为java
        if (questionSubmitQueryDTO.getLanguage() == null) {
            questionSubmitQueryDTO.setLanguage(QuestionSubmitLanguageEnum.JAVA.getValue());
        }
        //获取用户信息
        User loginUser = userFeignClient.getLoginUser(request);
        ThrowUtils.throwIf(loginUser == null, ErrorCode.NOT_LOGIN_ERROR);
        //获取题目信息
        Question question = questionService.getById(questionSubmitQueryDTO.getQuestionId());
        if (question == null) {
            throw new BusinessException(ErrorCode.NOT_FOUND_ERROR);
        }
        //定义缓存键
        String cacheKey= CACHE_KEY_PREFIX+question.getId()+questionSubmitQueryDTO.getLanguage();
        // 尝试从Redis中获取缓存
        AiQuestionVO cachedAiQuestionVO = (AiQuestionVO) redisTemplate.opsForValue().get(cacheKey);
        if (cachedAiQuestionVO != null) {
            // 如果缓存存在，直接返回
            return ResultUtils.success(cachedAiQuestionVO);
        } else {
            // 限流判断，每个用户一个限流器(如果缓存中有该题目的ai答题，就不用去限流，因为不消耗ai的资源)
            redisLimiterManager.doRateLimit("aiQuestion_"+loginUser.getId());
            // 如果缓存不存在，调用AI方法获取结果
           // AiQuestionVO aiQuestionVO = aiManager.getGenResultByDeepSeek(question.getTitle(), question.getContent(), questionSubmitQueryDTO.getLanguage(), question.getId());

            // 如果缓存不存在，调用AI方法获取结果(该造为调用ai的工厂来调用不同的ai模型（aiModel）)
            //然后ai模型调用方法，获取到AiQuestionVO
            AiModel aiModel = aiMangerFactory.newInstance(questionSubmitQueryDTO.getAiModel());
            AiQuestionVO aiQuestionVO = aiModel.getGenResult(question.getTitle(), question.getContent(), questionSubmitQueryDTO.getLanguage(), question.getId());
            // 将结果存入Redis并设置过期时间为一天
            redisTemplate.opsForValue().set(cacheKey, aiQuestionVO, 24, TimeUnit.HOURS);
            return ResultUtils.success(aiQuestionVO);
        }

    }

}
